package com.dayuanit.booksystem.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class BaseServlet extends HttpServlet {

    /**
     * 统一响应方法
     * @param msg 响应的内容
     * @param response  response对象
     * @throws ServletException
     * @throws IOException
     */
    protected void sendResultToClient(String msg, HttpServletResponse response) throws ServletException, IOException {
        //设置响应头，告诉我们的终端，返回的内容以及编码集
        response.setContentType("text/html; charset=utf-8");

        //通过response对象，获得输出流，将结果响应给客户端。
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(msg.getBytes("utf-8"));
        outputStream.flush();
    }

    /**
     * 统一响应方法 AJax
     * @param msg 响应的内容
     * @param response  response对象
     * @throws ServletException
     * @throws IOException
     */
    protected void sendResultToClient4Ajax(String msg, HttpServletResponse response) throws ServletException, IOException {
        //设置响应头，告诉我们的终端，返回的内容以及编码集
        response.setContentType("application/json; charset=utf-8");

        //通过response对象，获得输出流，将结果响应给客户端。
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(msg.getBytes("utf-8"));
        outputStream.flush();
    }
}
